
var app = getApp()
var Bmob = require('../../utils/bmob.js');
Page({
  data: {
    editing: false,//是否在编辑
    goodsCount: 0,//商品数量
    goodsCountToPay: 0,//商品去支付的数量
    priceToPay: 0.00,
    goodsList: [],
    selectAll: false,
    editSelectAll: false,
    timeout: null,
    isFromBack: false,
    notBussinessTimeGoodId: []
  },
  franchiseeId: '',
  isFromUserCenterEle: '',
  onLoad: function(options){
    this.franchiseeId = options.franchisee || '';
    this.isFromUserCenterEle = options.from || '';
    this.getShoppingCartData();
  },
  onShow: function(){
    if(this.data.isFromBack){
      this.getShoppingCartData();
      this.setData({
        selectAll: false
      });
    } else {
      this.setData({
        isFromBack: true
      });
    }

    // app.checkIfBindPhone();
  },
  getShoppingCartData: function () {
    var that = this;
   
     var franchiseeId = this.franchiseeId,
      fromUserCenterEle = this.data.isFromUserCenterEle;
    var ShoppingCarts = Bmob.Object.extend("shoppingCart");
    var shoppingCart = new Bmob.Query(ShoppingCarts);
    var currentUser = Bmob.User.current();
    var objectId = currentUser.id;
    var isme = new Bmob.User();
    isme.id = objectId;     //当前用户的objectId
    shoppingCart.equalTo("users", isme);
   
    shoppingCart.include("goodsInfo");
  ///  shoppingCart.equalTo("shopping_car_id", "bmob");
    shoppingCart.find({
      success: function (res) {
        var data=[];
      
        if (res.length) {
          for (var i = 0; i <= res.length - 1; i++) {
           
            data.push(res[i].attributes);
            data[i].id = res[i].id;
          }
        } else {
          data = res.attributes;
        }

        that.setData({
          goodsList: data,
          goodsCount: res.length,
        });
        that.clickSelectAll();
        that.getTostoreNotBusinessTime();
        that.recalculateCountPrice();
      }
    })

    // 获取购物车列表时 传sub_shop_app_id获取
  
  },
  getShoppingCartData1: function(){
    var that = this,
        franchiseeId = this.franchiseeId,
        fromUserCenterEle = this.data.isFromUserCenterEle;

    // 获取购物车列表时 传sub_shop_app_id获取
    app.sendRequest({
      url: '/index.php?r=AppShop/cartList',
      data: {
        page: 1,
        page_size: 1000,
        sub_shop_app_id: fromUserCenterEle ? '' : franchiseeId,
        parent_shop_app_id: franchiseeId ? app.getAppId() : ''
      },
      success: function(res){
        for (var i = res.data.length - 1; i >= 0; i--) {
          var modelArr = res.data[i].model_value;

          if(modelArr && modelArr.join){
            res.data[i].model_value_str = '('+modelArr.join('|')+')';
          }
        }
        that.setData({
          takeoutInfo: res.take_out_info,
          goodsCount: res.data.length,
          goodsList: res.data
        });
        that.clickSelectAll();
        that.getTostoreNotBusinessTime();
        that.recalculateCountPrice();
      }
    })
  },
  switchToEdit: function(){
    this.setData({
      editing: true
    })
  },
  editComplete: function(){
    var list = this.data.goodsList;

    for (var i = list.length - 1; i >= 0; i--) {
      list[i].editSelected = false;
    }

    this.setData({
      editing: false,
      goodsList: list
    })
    this.recalculateCountPrice();
  },
  clickSelectAll: function(){
    var alreadySelect = this.data.selectAll;
    var that=this;
    var  list = [];
    if (that.data.goodsList)
    list=that.data.goodsList;
      
    if(alreadySelect){
      for (var i = list.length - 1; i >= 0; i--) {
        list[i].selected = false;
      }
    } else {
      for (var i = list.length - 1; i >= 0; i--) {
        list[i].selected = true;
      }
    }
    this.setData({
      selectAll: !alreadySelect,
      goodsList: list
    })
    this.recalculateCountPrice();
  },
  //检查商品的状态，是否超出秒杀的数量
  getTostoreNotBusinessTime: function (payIdArr , sucfn){
    var that = this;
    sucfn && sucfn();
   
  },
  clickEditSelectAll: function(){
    var alreadySelect = this.data.editSelectAll,
        list = this.data.goodsList;

    if(alreadySelect){
      for (var i = list.length - 1; i >= 0; i--) {
        list[i].editSelected = false;
      };
    } else {
      for (var i = list.length - 1; i >= 0; i--) {
        list[i].editSelected = true;
      };
    }

    this.setData({
      editSelectAll: !alreadySelect,
      goodsList: list
    })
  },
  clickSelectGoods: function(e){
    var index = e.currentTarget.dataset.index,
        list = this.data.goodsList,
        selectAll = true;

    list[index].selected = !list[index].selected;
    for (var i = list.length - 1; i >= 0; i--) {
      if(!list[i].selected){
        selectAll = false;
        break;
      }
    }
    this.setData({
      goodsList: list,
      selectAll: selectAll
    })
    this.recalculateCountPrice();
  },
  clickEditSelectGoods: function(e){
    var index = e.currentTarget.dataset.index,
        list = this.data.goodsList,
        editSelectAll = true;

    list[index].editSelected = !list[index].editSelected;
    for (var i = list.length - 1; i >= 0; i--) {
      if(!list[i].editSelected){
        editSelectAll = false;
        break;
      }
    }
    this.setData({
      goodsList: list,
      editSelectAll: editSelectAll
    })
  },
  recalculateCountPrice: function(){
    var list = this.data.goodsList,
        totalCount = 0,
        price = 0;

    for (var i = list.length - 1; i >= 0; i--) {
      var goods = list[i];
      
      if(goods.selected){
        totalCount += +goods.num;
        price += +goods.price * +goods.num;
      }
    }

    this.setData({
      goodsCountToPay: totalCount,
      priceToPay: price.toFixed(2)
    })
  },
  deleteGoods: function(){
    var deleteIdArr = [],
        list = this.data.goodsList,
        listExcludeDelete = [],
        franchiseeId = this.franchiseeId,
        fromUserCenterEle = this.data.isFromUserCenterEle,
        that = this;
    var ShoppingCarts = Bmob.Object.extend("shoppingCart");
    var shoppingCart = new Bmob.Query(ShoppingCarts);
    for (var i = list.length - 1; i >= 0; i--) {
      if(list[i].editSelected){
        deleteIdArr.push(+list[i].id);
        shoppingCart.get(list[i].id, {
          success: function (object) {
            // The object was retrieved successfully.
            object.destroy({
              success: function (deleteObject) {
                console.log('删除日记成功');
                //deleteIdArr.push(+list[i].id);
               
              },
              error: function (object, error) {
                console.log('删除日记失败');
              }
            });
          },
          error: function (object, error) {
            console.log("query object fail");
          }
        });
        
      } else {
        listExcludeDelete.push(list[i]);
      }
    }

    if(!deleteIdArr.length) { return; }
    that.setData({
      goodsList: listExcludeDelete,
      goodsCount: listExcludeDelete.length
    })
   
  },
  goToPay: function(e){
    var payIdArr = [],
        list = this.data.goodsList,
        franchiseeId = this.franchiseeId,
        fromUserCenterEle = this.data.isFromUserCenterEle,
        selectGoodsType = '',
        cartIdArray = [],
        sameGoodsType = true,
        that = this,
        notBusinessTimeFlag = false;
console.log("fdsafsda")

    for (var i = list.length - 1; i >= 0; i--) {
      var li = list[i];
     // console.log(li.goods)
      if(li.selected){
        selectGoodsType = selectGoodsType == '' ? li.goodsInfo.goods_type : selectGoodsType;
        if (sameGoodsType && selectGoodsType != li.goodsInfo.goods_type){
          sameGoodsType = false;
        }
        cartIdArray.push(li.id);
        payIdArr.push({
          cart_id: li.id,
          goods_id: li.goods_id,
          model_id: li.model_id,
          model: li.models,
          num: li.num,
          goods_type: li.goodsInfo.goods_type
        });
       
      }
    }
   
    if(!payIdArr.length) {
      app.showModal({
        content: '请选择结算的商品'
      });
      return;
    }
    if(sameGoodsType){
      // 当购物车勾选商品种类全部相同时 不生成订单而是跳转到预览订单页面
      that.getTostoreNotBusinessTime(payIdArr , function() {
        if(selectGoodsType == 0){
          //全部为电商
          var pagePath = '/pages/previewGoodsOrder/previewGoodsOrder?cart_arr='+encodeURIComponent(cartIdArray);

          franchiseeId && (pagePath += '&franchisee=' + franchiseeId);
          app.turnToPage(pagePath);
          // return;

        } else if (selectGoodsType == 1) {
          //全部为预约
          var pagePath = '/pages/previewAppointmentOrder/previewAppointmentOrder?cart_arr=' + encodeURIComponent(cartIdArray);

          franchiseeId && (pagePath += '&franchisee=' + franchiseeId);
          app.turnToPage(pagePath);
          // return;
        }else if (selectGoodsType == 3){
          //全部为到店
          var pagePath = '/pages/previewOrderDetail/previewOrderDetail?cart_arr='+encodeURIComponent(cartIdArray);

          franchiseeId && (pagePath += '&franchisee=' + franchiseeId);
          app.turnToPage(pagePath);
          // return;
        } else if (selectGoodsType == 2){
          if(+that.data.takeoutInfo.min_deliver_price > +that.data.priceToPay){
            app.showModal({
              content: '没有达到起送价('+that.data.takeoutInfo.min_deliver_price+'元)'
            });
            return;
          }
          var pagePath = '/pages/previewTakeoutOrder/previewTakeoutOrder?cart_arr=' + encodeURIComponent(cartIdArray);

          franchiseeId && (pagePath += '&franchisee=' + franchiseeId);
          app.turnToPage(pagePath);
        }
      });
    }else{
       app.showModal({
        content: '商品混合，不可下单，请重新选择。'
      });
    }

  },
  clickMinusButton: function(e){
    var index = e.currentTarget.dataset.index,
        num = this.data.goodsList[index].num,
       // console.log(num)
        fromUserCenterEle = this.data.isFromUserCenterEle,
        franchiseeId = this.franchiseeId,
        deleteId = this.data.goodsList[index].id,
        that = this;
    var ShoppingCarts = Bmob.Object.extend("shoppingCart");
    var shoppingCart = new Bmob.Query(ShoppingCarts);
       
    if(num-1 <= 0){
      app.showModal({
        content: '确定从购物车删除该商品？',
        showCancel: true,
        confirm: function () {
         
          shoppingCart.get(deleteId, {
            success: function (object) {
              // The object was retrieved successfully.
              object.destroy({
                success: function (deleteObject) {
                  console.log('删除日记成功');
                  //deleteIdArr.push(+list[i].id);
                  that.setData({
                    selectAll: false
                  });
                  that.getShoppingCartData();
                },
                error: function (object, error) {
                  console.log('删除日记失败');
                }
              });
            },
            error: function (object, error) {
              console.log("query object fail");
            }
          });
         
      
        }
      })
      return;
    }
    this.changeGoodsNum(index, 'minus');
  },
  clickPlusButton: function(e){
    var index = e.currentTarget.dataset.index;
    var goodsInfo=this.data.goodsList[index].goodsInfo;
   
  
    var subNameIndex = this.data.goodsList[index].subNameIndex;
    var modelNameIndex = this.data.goodsList[index].modelNameIndex;
   
    var count = this.data.goodsList[index].num;
    var stock = goodsInfo.models[subNameIndex].models[modelNameIndex].stock;
  

    if (count >= stock) {
      app.showModal({ content: '购买数量不能大于库存' });
      return;
    }
   
    if (goodsInfo.is_seckill && count >= goodsInfo.seckill_buy_limit) {
      app.showModal({ content: '购买数量不能大于秒杀限购数量' });
     
      return;
    }
    this.setData({
      'selectModelInfo.buyCount': count + 1
    });
    this.changeGoodsNum(index, 'plus');
  },


  changeGoodsNum: function (index, type) {
    var goods = this.data.goodsList[index],
      goodsId = goods.id,
      currentNum = +goods.num,
      targetNum = type == 'plus' ? currentNum + 1 : currentNum - 1,
 
      that = this,
      data = {},
      param;
  
    var ShoppingCarts = Bmob.Object.extend("shoppingCart");
    var shoppingCart = new Bmob.Query(ShoppingCarts);
    var subNameIndex=goods.subNameIndex;
    var modelNameIndex = goods.modelNameIndex;
    var stock;
   
    if(goods.is_seckill)
    stock=goods.goodsInfo.models[subNameIndex].models[modelNameIndex].seckill_stock;
    else
    { stock = goods.goodsInfo.models[subNameIndex].models[modelNameIndex].stock;} 
    
       

    if (targetNum > stock) {
      app.showModal({
        content: '库存不足'
      });
      return;
    }

    
    shoppingCart.get(goodsId, {
      success: function (result) {
        // 回调中可以取得这个 diary 对象的一个实例，然后就可以修改它了
        result.set('num', targetNum);
        result.save({

          success: function () {
           
            data = {};
            data['goodsList[' + index + '].num'] = targetNum;
            that.setData(data);
            that.recalculateCountPrice();
          },
                    
          });
     
      },
      error: function (object, error) {

      }
    });


  },
  changeGoodsNum1: function(index, type){
    var goods = this.data.goodsList[index],
        currentNum = +goods.num,
        targetNum = type == 'plus' ? currentNum + 1 : currentNum - 1,
        that = this,
        data = {},
        param;
    if (targetNum > goods.stock ){
      app.showModal({
        content: '库存不足'
      });
      return;
    }

    param = {
      goods_id: goods.goods_id,
      model_id: goods.model_id || '',
      num: targetNum,
      sub_shop_app_id: this.franchiseeId,
      is_seckill : goods.is_seckill == 1 ? 1 : ''
    };

    app.sendRequest({
      url: '/index.php?r=AppShop/addCart',
      data: param,
      success: function (res) {
        data = {};
        data['goodsList[' + index + '].num'] = targetNum;
        that.setData(data);
        that.recalculateCountPrice();
      },
      successStatusAbnormal: function(res){
        app.showModal({
          content: res.data
        })
      }
    })
  },
  inputGoodsCount: function(e){
    var index = e.target.dataset.index,
        count = e.detail.value,
        data = {};
    var goodsInfo = this.data.goodsList[index].goodsInfo;
   
    var subNameIndex = this.data.goodsList[index].subNameIndex;
    var modelNameIndex = this.data.goodsList[index].modelNameIndex;
    var stock = goodsInfo.models[subNameIndex].models[modelNameIndex].stock;
  
    if (count >= stock) {
      app.showModal({ content: '购买数量不能大于库存' });
      return;
    }

    if (goodsInfo.is_seckill && count >= goodsInfo.seckill_buy_limit) {
      app.showModal({ content: '购买数量不能大于秒杀限购数量' });

      return;
    }
    data['goodsList['+index+'].num'] = +count;
    this.setData(data);
  }
})
